package com.polaris.live.utils

import android.content.Context
import androidx.activity.ComponentActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleOwner
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.AppException
import com.polaris.live.common.network.request
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.constant.LiveConst
import com.polaris.live.constant.LiveConst.SenderFormType
import com.polaris.live.constant.UserConst
import com.polaris.live.constant.UserConst.FromType
import com.polaris.live.im.sfs.bean.live.ext.UserBasicVo
import com.polaris.live.net.homeService
import com.polaris.live.net.liveService
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.back_resp.CallStartResp
import com.polaris.live.resp.back_resp.MatchStartResp
import com.polaris.live.resp.event.CallEndEvent
import com.polaris.live.resp.go_resp.CallStartBean
import com.polaris.live.resp.go_resp.MatchStartBean
import com.polaris.live.translation.R
import com.polaris.live.utils.route.RoutePath
import com.polaris.live.utils.route.Router
import org.greenrobot.eventbus.EventBus

/**
 * 拨打视频代理类
 *
 * @author Created by 半仙 on 2023/10/25/025 21:24
 */
object StartCallProxy {

    /**
     * builder
     */
    fun builder(activity: ComponentActivity): CallStartBuilder {
        return CallStartBuilder(activity, activity)
    }

    /**
     * builder
     */
    fun builder(fragment: Fragment): CallStartBuilder {
        return CallStartBuilder(fragment, fragment.requireContext())
    }

    /**
     * builder
     */
    fun builder(owner: LifecycleOwner, context: Context): CallStartBuilder {
        return CallStartBuilder(owner, context)
    }

    class CallStartBuilder internal constructor(
        private val owner: LifecycleOwner,
        private val context: Context
    ) {

        /**
         * 新人邀约拨打电话
         *
         * @param viewModel       viewModel
         * @param formType         通话来源 不同页面需要不同的值
         * @param otherId         对方id
         * @param senderFrom       1手动 2匹配 3邀约
         * @param userBasic       对方的基本信息
         * @param onSuccess         成功回调
         * @param onError           失败回调
         */
        fun startNoticeCall(
            viewModel: BaseViewModel,
            @FromType formType: Int,
            @UserConst.LastFromType lastFromType: Int,
            @SenderFormType senderFrom: Int,
            otherId: Long,
            userBasic: UserBasicVo? = null,
            matchId: Long? = null,
            onSuccess: ((CallStartResp) -> Unit)? = null,
            onError: (AppException) -> Unit = {},
        ) {
            invokeStartCall(
                owner,
                context,
                viewModel,
                formType,
                lastFromType,
                otherId,
                senderFrom,
                matchId,
                null,
                userBasic,
                onSuccess,
                onError
            )
        }

        /**
         * 主动拨打电话
         *
         * @param viewModel       viewModel
         * @param formType         通话来源 不同页面需要不同的值
         * @param otherId         对方id
         * @param senderFrom       1手动 2匹配 3邀约
         * @param userBasic       对方的基本信息
         * @param onSuccess         成功回调
         * @param onError           失败回调
         */
        fun startCall(
            viewModel: BaseViewModel,
            @FromType formType: Int,
            @UserConst.LastFromType lastFromType: Int,
            @SenderFormType senderFrom: Int,
            otherId: Long,
            userBasic: UserBasicVo? = null,
            onSuccess: ((CallStartResp) -> Unit)? = null,
            onError: (AppException) -> Unit = {},
        ) {
            invokeStartCall(
                owner,
                context,
                viewModel,
                formType,
                lastFromType,
                otherId,
                senderFrom,
                null,
                null,
                userBasic,
                onSuccess,
                onError
            )
        }

        /**
         * 匹配用的startCall
         *
         * @param viewModel       viewModel
         * @param formType         通话来源 不同页面需要不同的值
         * @param otherId         对方id
         * @param senderFrom       1手动 2匹配 3邀约
         * @param matchId        匹配id 2匹配 3邀约 都需要给matchId
         * @param userBasic       对方的基本信息
         * @param onSuccess      成功回调
         * @param onError         失败回调
         */
        fun startCall(
            viewModel: BaseViewModel,
            @FromType formType: Int,
            @UserConst.LastFromType lastFromType: Int,
            @SenderFormType senderFrom: Int,
            otherId: Long,
            userBasic: UserBasicVo? = null,
            matchId: Long,
            onSuccess: ((CallStartResp) -> Unit)? = null,
            onError: (AppException) -> Unit = {},
        ) {
            invokeStartCall(
                owner,
                context,
                viewModel,
                formType,
                lastFromType,
                otherId,
                senderFrom,
                matchId,
                null,
                userBasic,
                onSuccess,
                onError
            )
        }

        /**
         * 开启匹配
         *
         * @param viewModel       viewModel
         * @param onSuccess         成功回调
         * @param onError           失败回调
         */
        fun startMatch(
            viewModel: BaseViewModel,
            onSuccess: ((matchStartResp: MatchStartResp) -> Unit)? = null,
            onError: (AppException) -> Unit = {},
        ) {
            val type = 1
            StartLiveProxy.checkRoomState(owner) {
                viewModel.request(
                    { homeService.matchStart(MatchStartBean(type, UserConst.From.CALL_END)) },
                    {
                        onSuccess?.invoke(it)
                        Router.builder(RoutePath.LIVE_MATCH_ACTIVIYT)
                            .withInt("page", UserConst.From.CALL_END)
                            .withInt("lastPage", UserConst.LastFrom.CALL_END)
                            .withLong("id", it.id)
                            .navigation()

                    }, {
                        ToastGravity.showGravity(it.errorMsg)
                        onError.invoke(it)
                    })
            }
        }
    }

    /**
     * 主动拨打电话
     * formType         通话来源 不同页面需要不同的值
     * senderFrom       1手动 2匹配 3邀约
     */
    private fun invokeStartCall(
        owner: LifecycleOwner,
        context: Context,
        viewModel: BaseViewModel,
        formType: Int,
        lastFromType: Int,
        otherId: Long,
        senderFrom: Int,
        matchId: Long?,
        gameType: Int?,
        userBasic: UserBasicVo?,
        onSuccess: ((CallStartResp) -> Unit)?,
        onError: (AppException) -> Unit = {},
    ) {
        GlobalPopupManager.showCompletePopup(context) {
            StartLiveProxy.checkRoomState(owner) {
                StartLiveProxy.permissionVideo(context, {
                    viewModel.requestLoading(
                        {
                            liveService.callStart(
                                CallStartBean(
                                    formType,
                                    lastFromType,
                                    otherId,
                                    senderFrom,
                                    matchId,
                                    gameType = gameType
                                )
                            )
                        },
                        {
                            onSuccess?.invoke(it)

                            if (it.call.status !in LiveConst.CallState.successStates) {
                                ToastGravity.showGravity(R.string.error_data)
                                return@requestLoading
                            }

                            EventBus.getDefault().post(CallEndEvent())

                            Router.builder(RoutePath.CALL_VIDEO_ACTIVITY)
                                .withInt(LiveConst.Params.CALL_FROM_TYPE, formType)
                                .withInt(LiveConst.Params.CALL_LAST_FROM_TYPE, lastFromType)
                                .withInt(LiveConst.Params.CALL_ROLE, LiveConst.CallRole.CALLER)
                                .withAny(LiveConst.Params.CALL_BEAN, it)
                                .withAnyNullable(LiveConst.Params.CALL_USER_BASIC, userBasic)
                                .navigation()
                        }, {
                            ToastGravity.showGravity(it.errorMsg)
                            onError.invoke(it)
                        },
                        message = R.string.start_call_loading,
                        waitTime = 0L
                    )
                })
            }
        }
    }

}